package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.filter.Filters;
import com.otaliastudios.cameraview.gesture.Gesture;
import com.otaliastudios.cameraview.gesture.GestureAction;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;
import com.stark.camera.kit.filter.customfilter.CartoonFilter;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.CameraFilterAdapter;
import flc.ast.bean.MyCameraFilterBean;
import flc.ast.databinding.ActivityCameraBinding;
import flc.ast.utils.Content;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.WorkPathUtil;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private int shotTime = 0;//拍摄延迟
    private float myBrightness = 1;//亮度
    private int number;//拍照倒计时
    private CameraOptions mCameraOptions;
    private Handler mHandler;
    private int mRecordTime;//拍摄视频的时间
    private boolean isShoot = false;
    //滤镜
    private CameraFilterAdapter filterAdapter;
    private int oldFilterPos = 0;

    @Override
    protected int onCreate() {
        return R.layout.activity_camera;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);
        mDataBinding.ivCameraFilter.setOnClickListener(this);
        mDataBinding.ivCameraDelay.setOnClickListener(this);
        mDataBinding.ivCameraTouch.setOnClickListener(this);
        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.tvCameraPicture.setOnClickListener(this);
        mDataBinding.tvCameraVideo.setOnClickListener(this);
        mDataBinding.ivFilterBack.setOnClickListener(this);
        mDataBinding.llBottomMain.setOnClickListener(null);
        mHandler = new Handler();
        mRecordTime = 0;
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivCameraReversal://镜头反转
                reversalLens();
                break;
            case R.id.ivCameraDelay://延时拍摄
                openDelayShot();
                break;
            case R.id.ivCameraTouch://触屏拍摄
                openTouchShot();
                break;
            case R.id.ivCameraFlash:
                //闪光灯
                openFlash();
                break;
            case R.id.ivCameraStart://开始拍摄
                startShot();
                break;
            case R.id.ivCameraFilter://滤镜
                mDataBinding.llBottomMain.setVisibility(View.GONE);
                mDataBinding.llBottomFilter.setVisibility(View.VISIBLE);
                break;
            case R.id.ivFilterBack://滤镜返回
                mDataBinding.llBottomMain.setVisibility(View.VISIBLE);
                mDataBinding.llBottomFilter.setVisibility(View.GONE);
                break;
            case R.id.tvCameraPicture://拍摄图片模式
                isShoot = false;
                mDataBinding.rlVideoLog.setVisibility(View.GONE);
                mDataBinding.tvCameraPicture.setVisibility(View.INVISIBLE);
                mDataBinding.tvCameraVideo.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraMode.setText(R.string.shoot_picture);
                mDataBinding.cameraView.setMode(Mode.PICTURE);
                break;
            case R.id.tvCameraVideo://拍摄视频模式
                getRecordPermission();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        //设置滤镜
        filterAdapter.getItem(oldFilterPos).setSelect(false);
        oldFilterPos = position;
        filterAdapter.getItem(position).setSelect(true);
        filterAdapter.notifyDataSetChanged();
        mDataBinding.cameraView.setFilter(filterAdapter.getItem(position).getFilter());
    }

    @Override
    protected void initData() {
        getPermission();
        //滤镜数据
        List<MyCameraFilterBean> mFilterList = new ArrayList<>();//滤镜集合
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text1), "#00000000", Filters.values()[0].newInstance(), true));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text2), "#323333", Filters.values()[1].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text3), "#C376F3", Filters.values()[2].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text4), "#6F7171", Filters.values()[3].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text5), "#505151", Filters.values()[4].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text6), "#999999", Filters.values()[5].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text7), "#513232", Filters.values()[6].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text8), "#787A7A", Filters.values()[7].newInstance(), false));
        mDataBinding.rvFilterList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        filterAdapter = new CameraFilterAdapter();
        mDataBinding.rvFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
        filterAdapter.setList(mFilterList);
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
                setCameraPar();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    private void getRecordPermission(){
        StkPermissionHelper.permission(Manifest.permission.RECORD_AUDIO).reqPermissionDesc(getString(R.string.get_record_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                isShoot = true;
                mDataBinding.rlVideoLog.setVisibility(View.VISIBLE);
                mDataBinding.tvVideoNum.setText("00:00");
                mDataBinding.tvCameraPicture.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraVideo.setVisibility(View.INVISIBLE);
                mDataBinding.tvCameraMode.setText(R.string.shoot_video);
                mDataBinding.cameraView.setMode(Mode.VIDEO);
                mDataBinding.cameraView.setAudio(Audio.ON);
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                mCameraOptions = options;
            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                //获取图片 去到预览界面
                int picWidth = result.getSize().getWidth();
                int picHeight = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (picWidth * picHeight > screenWidth * screenHeight) {
                    picWidth = screenWidth;
                    picHeight = screenHeight;
                }
                result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        //去到对应结果界面
                        PreviewActivity.isVideo = false;
                        PreviewActivity.resultImg = bitmap;
                        startActivity(PreviewActivity.class);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {
                //开始拍摄视频
                startRecordTime();
            }

            @Override
            public void onVideoRecordingEnd() {
                //视频拍摄结束
                mDataBinding.tvVideoNum.setText("00:00");
                stopRecordTime();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                //获取视频 去到预览界面
                PreviewActivity.isVideo = true;
                PreviewActivity.resultPath = result.getFile().getPath();
                startActivity(PreviewActivity.class);
            }
        });
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

    //打开延时拍摄
    private void openDelayShot() {
        if (SPUtil.getBoolean(mContext, Content.isDelay, false)) {
            shotTime = 0;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.yanshiguan1);
            SPUtil.putBoolean(mContext, Content.isDelay, false);
            shotTipText(getString(R.string.delay_close));
        } else {
            shotTime = 3000;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.s3);
            SPUtil.putBoolean(mContext, Content.isDelay, true);
            shotTipText(getString(R.string.delay_open));
        }
    }

    //打开触屏拍摄
    private void openTouchShot() {
        GestureAction action = mDataBinding.cameraView.getGestureAction(Gesture.TAP);
        if (action == GestureAction.NONE) {
            mDataBinding.ivCameraTouch.setImageResource(R.drawable.chupingpai2);
            mDataBinding.cameraView.mapGesture(Gesture.TAP, GestureAction.TAKE_PICTURE_SNAPSHOT);
            shotTipText(getString(R.string.touch_shot_open));
        } else {
            mDataBinding.ivCameraTouch.setImageResource(R.drawable.chupingpai1);
            mDataBinding.cameraView.clearGesture(Gesture.TAP);
            shotTipText(getString(R.string.touch_shot_close));
        }
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.shanguangdeng2);
            shotTipText(getString(R.string.flash_close));
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.shanguangdeng1);
            shotTipText(getString(R.string.flash_open));
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }


    //显示提示文字
    private void shotTipText(String text) {
        mDataBinding.tvCameraTipText.setText(text);
        mDataBinding.tvCameraTipText.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mDataBinding.tvCameraTipText.setVisibility(View.GONE);
            }
        }, 500);
    }

    //开始拍摄
    private void startShot() {
        if (!isShoot) {//照片拍摄
            if (mDataBinding.cameraView.isTakingPicture()) return;
            //加个拍照延迟
            if (shotTime > 0) {
                delayNumber();//倒计时
            }
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mDataBinding.cameraView.takePictureSnapshot();
                }
            }, shotTime);
        } else {//视频拍摄
            if (mDataBinding.cameraView.isTakingVideo()) {
                mDataBinding.cameraView.stopVideo();
            } else {
                //加个拍照延迟
                if (shotTime > 0) {
                    delayNumber();//倒计时
                }
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        String filePath = WorkPathUtil.generateVideoFilePath(null);
                        if (filePath != null) {
                            mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                        }
                    }
                }, shotTime);
            }
        }
    }

    //倒计时
    private void delayNumber() {
        number = shotTime / 1000;
        new CountDownTimer(shotTime, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                mDataBinding.tvCameraDelayText.setVisibility(View.VISIBLE);
                //millisUntilFinished / 1000 会有不可描述的问题
                mDataBinding.tvCameraDelayText.setText("" + number--);
            }

            @Override
            public void onFinish() {
                mDataBinding.tvCameraDelayText.setVisibility(View.GONE);
            }
        }.start();
    }

    //回显相机设置
    private void setCameraPar() {
        if (SPUtil.getBoolean(mContext, Content.isDelay, false)) {
            shotTime = 3000;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.s3);
        } else {
            shotTime = 0;
            mDataBinding.ivCameraDelay.setImageResource(R.drawable.yanshiguan1);
        }
    }

    //开始拍摄视频
    private void startRecordTime() {
        mRecordTime = 0;
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
        mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束拍摄视频
    private void stopRecordTime() {
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
    }

    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mRecordTime++;
            mDataBinding.tvVideoNum.setText(TimeUtils.millis2String(mRecordTime * 1000L, "mm:ss"));
            mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
        }
    };

}